layui.define([ 'form', 'laydate', 'table'], function(exports) {
    var form = layui.form;
    var index = layui.index;
    var view = {
        init:function(){
        	windowAllRefresh();
        	  this.initSubmit();
        	  this.address();
        	  this.tax(); 
        	  this.coupon();
        },
        coupon:function(){
        	$(document).on('click','.canCouponUserVOs',function(){
        		$(".canCouponUserVOs").removeClass("atver");
        		$(this).addClass("atver");
        		$("#couponCode").val($(this).attr('couponCode'));
        		windowRefresh();
        	})
        },
        address:function(){
        		$(document).on('click','.view-title',function(){
        			$(".view-title").removeClass('active');
        			$(this).addClass('active');
        			$("#subAddressId").val($(this).attr('aria'));
        			var pickUp=$("#pickUp").val();
        			if(pickUp=="true"){//自提
        				//失去焦点事件
        				var shipMobile=$('.phone_name').val()//自提电话
            			var shipName=$('.phone_number').val()//自提收货人
            			if(shipMobile&&shipName){
            				windowRefresh();
            				$(".deliveryType").html("自提")
            			}
        			}else{//快递
        				windowRefresh();
        				$(".deliveryType").html("快递")
        			}
        			
        			
        		})
        	 //删除地址
	        $(document).on('click', '.delete-site', function () {
	            var t = $(this);
	            var addressId=t.attr('areaid');
	            var data = {'addressId': addressId};
	            $.confirm('友情提示', '确定删除收货地址', function () {
	            	 doAjax('/user/userAddress/removeAddress.json', 'post', data, function (res) {
		                        t.parents('li').remove();
		                        $.alert('success', '删除成功');
		                        if($('.view-shipping').eq(0).find('li').length>2)
		                        {
		                            $('.moer_adder').show();
		                        }
		                        else
		                        {
		                            $('.moer_adder').hide();
		                            $('.view-shipping').eq(0).css("height","auto");
		                        }
		                })
		                $(".popup-btn-close").click()
	                 });
	            refreshAddress();
	        })
	        //新增收货地址
		var index="";
		$(".compile-site").each(function(index, element) {
            $(element).attr("index",index)
        });
        $(document).on('click', '.new_add_site , .compile-site', function () {
        	var t=$(this).attr('id_alter');
     		if(!t){t=0;}
            doAjax('/html/addOrEditAddress.html', 'get', {'taxId':0}, function (res) {
            	if(t>0){
           		 doAjax('/user/userAddress/getAddressInfoById.json', 'post', {'addressId':t}, function (data) {
           			 var userAddress=data.data;
           			 $('#areaId').val(userAddress.areaId);//收货人地区Id
           			 $('#addressId').val(userAddress.addressId);//收货人地址Id
           			 $('.invoice_bill input').eq(1).val(userAddress.addr);//详情地址
           			 $('.invoice_bill input').eq(2).val(userAddress.name);//收货人
           			 $('.invoice_bill input').eq(3).val(userAddress.mobile);//手机号码
           			 $('.invoice_bill input').eq(4).val(userAddress.tel);//固定号码
           			 $('.invoice_bill input').eq(5).val(userAddress.zip);//邮编
           			 if(userAddress.defAddr){
           				 $('.check_add').val('1') ;
           				 $('.ico_check').addClass('active');
           			 }	else{
           				 $('.check_add').val('0') ;
           				 $('.ico_check').removeClass('active');
           			 }												 //是否默认
           			 
           			 
           		 })
              }
                $.prompt({
                    style: '',
                    title: '个人收货地址',
                    con: res,
                });
                if(t>0){
               	 doAjax('/user/userAddress/getAddressInfoById.json', 'post', {'addressId':t}, function (data) {
           			 var userAddress=data.data;
           			 $.select_add("add_select_site", region_Data, userAddress.areaId);//默认北京/北京市/东城区							
           		 })
               	
               }else{
               	$.select_add("add_select_site", region_Data, 3);//默认北京/北京市/东城区
               }
            }, '', 'html')
        	
        	
//			if($(this).attr("index"))
//			{
//				index=$(this).attr("index");	
//			}
//            site($(this).attr('areaid'),$(this).attr('addressId'));

        });
        //确认
        $(document).on('click','.addressAdd_sub',function(){
            if (!validForm_02.check(false)) {
                $('.invoice_bill li p').show();
                return;
            }
            var addressId=$("#addressId").val()?$("#addressId").val():"0",//地址ID
                name=$('.invoice_bill input').eq(3).val(),//收货人姓名：
                areaId=$('.input_addr').val(),//收货人地区id：
                addr=$('.invoice_bill input').eq(2).val(),//收货人地址
                zip=$('.invoice_bill input').eq(6).val(),//邮编
                tel=$('.invoice_bill input').eq(5).val(),//固定号码
                mobile=$('.invoice_bill input').eq(4).val(),//手机号码
                defAddr=$('.check_add input').val()=='1'?true:false;//是否默认
            var addressData={
            	addressId:addressId,
            	name:name,
            	areaId:areaId,
            	addr:addr,
            	zip:zip,
            	tel:tel,
            	mobile:mobile,
            	defAddr:defAddr
            }
            doAjax('/user/userAddress/saveOrUpdateAddress.json','post',{"addressData":JSON.stringify(addressData)},function(res){
            	 location.href = location.href;
            });
            $('.popup-btn-close').click();
        })
         $(document).on('click','.bill-but-false',function(){
            $('.popup-btn-close').click();
        })
        
         $(document).on('click','.qx_sub ',function(){
        	 $('.popup-btn-close').click();
        })
		
		//设为默认地址
        $(document).on('click', '.tacitly-site', function () {
            var t = $(this);
            var addressId=t.attr('areaid');
            var data = {'addressId': addressId};
            doAjax('/user/userAddress/updateDefAddr.json', 'post', data, function (res) {
            	$('.Default-adder').hide();
	            t.parents('li').find('.Default-adder').show();
	            $('.delete-site').show();
	            t.parents('li').find('.delete-site').hide();
	            $('.tacitly-site').show();
	            t.parents('li').find('.tacitly-site').hide();
         //   	 location.href = location.href;
            });
        })
       
        },
        tax:function(){
            //新增/编辑增值发票
            $(document).on('click','.newly i,.alter',function(){
            	var t=$(this).attr('id_alter');
            	if(!t){t=0;}
                doAjax('/html/addOrEditTax.html', 'get', {'taxId':t}, function (res) {
                	if(t>0){
                		 doAjax('/user/userTax/getTax.json', 'post', {'taxId':t}, function (data) {
                			 var userTax=data.data;
                			 $('.invoice_bill input').eq(0).val(userTax.taxCompany);
                			 $('.invoice_bill input').eq(1).val(userTax.taxIdentification);
                			 $('.invoice_bill input').eq(2).val(userTax.taxAddr);
                			 $('.invoice_bill input').eq(3).val(userTax.taxTel);
                			 $('.invoice_bill input').eq(4).val(userTax.taxAccountName);
                			 $('.invoice_bill input').eq(5).val(userTax.taxNumber);
                			 $('#taxId').val(t);
                		 })
                	}
                    $.prompt({
                        style: '',
                        title: '增值税专用发票',
                        con: res,
                    });
                }, '', 'html')
            })
            //确认增值税发票
            $(document).on('click','.taxAdd_sub',function(){

                if (!validForm_01.check(false)) {
                    $('.invoice_bill li p').show();
                    return;
                }
                var tax_company=$('.invoice_bill input').eq(0).val(),//公司名称：
                    tax_identification=$('.invoice_bill input').eq(1).val(),//纳税人识别号：
                    tax_company_addr=$('.invoice_bill input').eq(2).val(),//公司地址
                    tax_tel=$('.invoice_bill input').eq(3).val(),//开户行
                    tax_account_name=$('.invoice_bill input').eq(4).val(),//账号
                    tax_number=$('.invoice_bill input').eq(5).val(),//发票内容
//                    tax_content=$('.invoice_bill select').eq(0).val(),//发票内容
                    tax_id=$('#taxId').val()?$('#taxId').val():"0";
                var taxData={
                    taxAccountName:tax_account_name,
                    taxAddr:tax_company_addr,
                    taxCompany:tax_company,
                    taxId:tax_id,
                    taxIdentification:tax_identification,
                    taxNumber:tax_number,
                    taxTel:tax_tel
                }
                doAjax('/user/userTax/saveTax.json','post',{"taxData":JSON.stringify(taxData)},function(res){
                    showTax();
                });
                $('.popup-btn-close').click();


            })

            $(document).on('click','.bill-but-false',function(){
                $('.popup-btn-close').click();
            })
            
             $(document).on('click','.qx_sub ',function(){
            	 $('.popup-btn-close').click();
            })
            //选择中发票
            $(document).on('click','.zz_fapiao input[type=radio]',function(){
                $('.zz_fapiao tr').removeClass('atver');
                $(this).parents('tr').addClass('atver');
            })

            //个人发票
            $('.icvoice_input_pe').change(function(){
                if($(this).val()=='companyOrdinary')
                {
                    $('.invoice_select_list tr.fold').show();
                }else
                {
                    $('.invoice_select_list tr.fold').hide()
                }
            })
            
            //删除发票
            $(document).on('click','.omit',function(){
                var t=$(this).attr('omit_id');
                doAjax('/user/userTax/delTax.json','post',{'taxId':t},function(res){
                    if(res.code == '200')
                    {
                        $.alert('success','删除成功');
                        showTax();
                    }
                    else
                    {
                        $.alert('error','删除失败');
                    }

                })
            })
            
           
        	
        },
        initSubmit:function(){
        	
        	
        	 $(".action-submit-order").click(function(){
        		 if($(this).hasClass('alreadyClicked')){
        			 return;	
        		 }
        			if(!$("#subAddressId").val())
        			{
        				 $.alert('error','请选择收货地址');
        				return		
        			}
        			if($("#pickUp").val()=="true")
        			{
        				if($(".phone_name").val()==''||$(".phone_number").val()=='')
        				{
        					 $.alert('error','选择自提联系人或手机号码不能为空');
        					return	
        				}
        			}
        			var addressId=parseInt($('#subAddressId').val())//地址
        			var couponCode=$('#couponCode').val();//优惠劵
        			var shipMobile=$('.phone_name').val()//自提电话
        			var shipName=$('.phone_number').val()//自提收货人
        			var cartIds=$('#cartIds').val();
        			var cartType=$('#cartType').val();
        			var memo=$('#memo').val();
        			var requestData={
        	                cartIds:cartIds,
        	                addressId:addressId,
        	                couponCode:couponCode,//优惠卷id
        	                memo:memo,
        	                shipMobile:shipMobile,
        	                shipName:shipName,
        	                operateType:"addcart"
        	            }
        			if(cartType){
        				requestData['cartType']=cartType;
        			}
        	 			var json={}
        	            var payment=$('input[name="payment[tax_type]"]:checked').val()//发票类型
        	            var taxType=$('#taxType').val();
        	 			if(taxType=='personal'){
        	 				payment='personal';
        	 			}else if(taxType=='companyOrdinary'){
        	 				payment='personal';
        	 			}else if(taxType=='companySpecial'){
        	 				payment='company';
        	 			}
        				  if(payment=='personal'){//普通发票
        	                requestData['taxType']=$('.icvoice_input_pe').val();//个人或公司
        	                requestData['taxContent']=$('#for_tax_content').val().toString();
        	                if($('.icvoice_input_pe').val()=='companyOrdinary'){
        	                	if(!$('#for_tax_company_01').val())
        	        			{
        	        				 $.alert('error','请填写纳税人识别号');
        	        				return		
        	        			}
        	                	if(!$('#for_tax_company_02').val())
        	        			{
        	        				 $.alert('error','请填写发票抬头');
        	        				return		
        	        			}
        	                    requestData['taxIdentification']=$('#for_tax_company_01').val();//识别码
        	                    requestData['taxCompany']=$('#for_tax_company_02').val();//识别码

        	                }
        	            }else if(payment=="company"){//公司发票

        	                if($('input[name="tax_id"]:checked'))
        	                {
        	                    if(!$('input[name="tax_id"]:checked').val()){
        	                        $.alert('error','请选择发票');
        	                        location.href = "#for_invoice_company";
        	                        return false;
        	                    }
        	                    var tr=$('input[name="tax_id"]:checked').parents('tr').find('.icvoice_tr_json');
        	                    requestData["taxId"]=tr.attr("name");
        	                    requestData["taxType"]='companySpecial';
        	                    requestData['taxContent']=$('input[name="tax_id"]:checked').parents('tr').find('.required_input_01').val().toString();
        	                }
        	            }else if(payment=="false")//默认页面
        	            	{
        	            	 requestData["taxId"]=$("#taxId").val();
        	            	 if($("#taxType").val()){
        	            		 requestData["taxType"]=$("#taxType").val();
        	        			}else{
        	        				requestData["taxType"]="unwanted";
        	        			}
        	            	 requestData["taxContent"]=$("#taxContent").val();
        	            	}
        	 			$(this).addClass('alreadyClicked');
        				doAjax('/order/popGoDown/settlementGoDown.json','post',{'requestData':JSON.stringify(requestData)},function(res){
        	                if(res.code=="200"){
        	                    $.alert('success','订单生产成功',1);
        	                    var data=res.data.data;
        	                    var orderId=data.orderId;
        	                    window.location.href='/order/popGoDown/goDownSucess.do?orderId='+orderId;
        	                }else if(res['code']==1212 || res['code']==1213 || res['code']==1216 || res['code']==1217){
        	                    $.confirm('',res['message'],function () {
        	                                                    window.location.href='http://www.11ziyun.com/goods'+'/'+res['data'][0]['sku'];
        	                                            },'',false,false);
        	                    return false;
        	                }else{
        	                    $.alert('error',res['message'],2);
        	                }
        	            })
        			/*-----------------------------------*/
        		})
        }
    }
    exports('gwcIndex',view);
	
});